昨天用了一般的NN來做影像分類,但其實同樣的情況用CNN會有效率很多,今天就來建立CNN再應用一次。
下載dataset和packages
import tensorflow as tf
from tensorflow import keras
fashion_mnist = keras.datasets.fashion_mnist
(X_train, y_train), (X_test, y_test) = fashion_mnist.load_data()
X_train = (X_train / 255.0).reshape(60000, 28, 28, 1)
X_test = (X_test / 255.0).reshape(10000, 28, 28, 1)
class_names = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat",
"Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]
開始建模,記得第一層layer要放input shape,layer中重要的參數有:
model = keras.models.Sequential()
model.add(keras.layers.Conv2D(filters=7, kernel_size=5, strides=1, padding="same", activation="relu",input_shape=[28, 28, 1]))
model.add(keras.layers.MaxPool2D(pool_size=2))
model.add(keras.layers.Conv2D(filters=7, kernel_size=3, strides=1, padding="same", activation="relu"))
model.add(keras.layers.MaxPool2D(pool_size=2))
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(50, activation="relu"))
model.add(keras.layers.Dense(50, activation="relu"))
model.add(keras.layers.Dropout(0.3))
model.add(keras.layers.Dense(10, activation="softmax"))
model.compile(loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"])
print(model.summary())
history = model.fit(X_train, y_train, epochs=10, validation_split=0.1)
model.evaluate(X_test, y_test)
[reference]
https://blog.csdn.net/zz2230633069/article/details/88544747
https://www.geeksforgeeks.org/keras-conv2d-class/
https://www.cnblogs.com/yjybupt/p/11646846.html
https://woj.app/6491.html